import {
  Request,
  Response,
  Router,
} from 'express';

import { IQuestion } from '@shared/types/question';

import { Question } from '../models/question.model';
import { EnumStatusCode } from '@shared/constant/enum';

export const questionRouter = Router();

// 获取试题列表（支持分页和筛选）
questionRouter.get("/list", async (req: Request, res: Response) => {
  try {
    const {
      page = 1,
      pageSize = 20,
      type,
      difficulty,
      keyword,
      creator
    } = req.query;

    const filter: any = {};
    if (type) filter.type = type;
    if (difficulty) filter.difficulty = difficulty;
    if (creator) filter.creator = creator;
    if (keyword) {
      filter.content = { $regex: keyword, $options: 'i' };
    }

    const limit = parseInt(pageSize as string);
    const skip = (parseInt(page as string) - 1) * limit;

    const questions = await Question.find(filter)
      .populate('creator', 'username')
      .skip(skip)
      .limit(limit)
      .sort({ create_time: -1 });

    const total = await Question.countDocuments(filter);

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "success",
      data: {
        data: questions,
        total_records: total,
        page: parseInt(page as string),
        limit,
        total_page: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取试题列表失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "获取试题列表失败",
      data: null
    });
  }
});

// 获取试题详情
questionRouter.get("/detail", async (req: Request, res: Response) => {
  try {
    const { id } = req.query;
    if (!id) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "试题ID不能为空",
        data: null
      });
    }

    const question = await Question.findById(id).populate('creator', 'username');
    if (!question) {
      return res.status(EnumStatusCode.NOT_FOUND).json({
        code: EnumStatusCode.NOT_FOUND,
        message: "试题不存在",
        data: null
      });
    }

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "success",
      data: question
    });
  } catch (error) {
    console.error('获取试题详情失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "获取试题详情失败",
      data: null
    });
  }
});

// 创建试题
questionRouter.post("/create", async (req: Request, res: Response) => {
  try {
    const questionData: IQuestion = req.body;
    
    // 验证必填字段
    if (!questionData.content || !questionData.type || !questionData.options || 
        !questionData.answer || !questionData.score || !questionData.difficulty) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "请填写完整的试题信息",
        data: null
      });
    }

    // 验证选项和答案
    if (questionData.type === 'Judgement' && questionData.options.length !== 2) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "判断题必须有2个选项",
        data: null
      });
    }

    if ((questionData.type === 'Select' || questionData.type === 'multiSelect') && 
        questionData.options.length !== 4) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "单选题和多选题必须有4个选项",
        data: null
      });
    }

    // 验证答案索引
    const maxIndex = questionData.options.length - 1;
    if (questionData.answer.some(index => index < 0 || index > maxIndex)) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "答案索引超出选项范围",
        data: null
      });
    }

    // 从认证用户中获取创建者ID
    questionData.creator = req.user?.user_id;

    const question = new Question(questionData);
    const savedQuestion = await question.save();

    res.status(EnumStatusCode.CREATED).json({
      code: EnumStatusCode.CREATED,
      message: "试题创建成功",
      data: savedQuestion
    });
  } catch (error) {
    console.error('创建试题失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "创建试题失败",
      data: null
    });
  }
});

// 更新试题
questionRouter.post("/update", async (req: Request, res: Response) => {
  try {
    const { id, ...updateData } = req.body;
    
    if (!id) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "试题ID不能为空",
        data: null
      });
    }

    // TODO: 检查试题是否被试卷引用，如果是则限制修改
    
    const updatedQuestion = await Question.findByIdAndUpdate(
      id,
      updateData,
      { new: true }
    ).populate('creator', 'username');

    if (!updatedQuestion) {
      return res.status(EnumStatusCode.NOT_FOUND).json({
        code: EnumStatusCode.NOT_FOUND,
        message: "试题不存在",
        data: null
      });
    }

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "试题更新成功",
      data: updatedQuestion
    });
  } catch (error) {
    console.error('更新试题失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "更新试题失败",
      data: null
    });
  }
});

// 删除试题
questionRouter.post("/delete", async (req: Request, res: Response) => {
  try {
    const { id, ids } = req.body;
    
    // TODO: 检查试题是否被试卷引用
    
    if (ids && Array.isArray(ids)) {
      // 批量删除
      const result = await Question.deleteMany({ _id: { $in: ids } });
      res.json({
        code: EnumStatusCode.SUCCESS,
        message: `成功删除 ${result.deletedCount} 道试题`,
        data: { deletedCount: result.deletedCount }
      });
    } else if (id) {
      // 单个删除
      const result = await Question.findByIdAndDelete(id);
      if (!result) {
        return res.status(EnumStatusCode.NOT_FOUND).json({
          code: EnumStatusCode.NOT_FOUND,
          message: "试题不存在",
          data: null
        });
      }
      res.json({
        code: EnumStatusCode.SUCCESS,
        message: "试题删除成功",
        data: null
      });
    } else {
      res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "请提供要删除的试题ID",
        data: null
      });
    }
  } catch (error) {
    console.error('删除试题失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "删除试题失败",
      data: null
    });
  }
});

// 批量导入试题
questionRouter.post("/import", async (req: Request, res: Response) => {
  try {
    const { questions } = req.body;
    
    if (!Array.isArray(questions) || questions.length === 0) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "请提供有效的试题数据",
        data: null
      });
    }

    // TODO: 验证每个试题的数据格式
    // TODO: 从JWT token中获取创建者ID
    
    const result = await Question.insertMany(questions);
    
    res.json({
      code: EnumStatusCode.SUCCESS,
      message: `成功导入 ${result.length} 道试题`,
      data: { importedCount: result.length }
    });
  } catch (error) {
    console.error('导入试题失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "导入试题失败",
      data: null
    });
  }
});

// 导出试题
questionRouter.get("/export", async (req: Request, res: Response) => {
  try {
    const { type, difficulty, creator } = req.query;
    
    const filter: any = {};
    if (type) filter.type = type;
    if (difficulty) filter.difficulty = difficulty;
    if (creator) filter.creator = creator;

    const questions = await Question.find(filter)
      .populate('creator', 'username')
      .sort({ create_time: -1 });

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "导出成功",
      data: questions
    });
  } catch (error) {
    console.error('导出试题失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "导出试题失败",
      data: null
    });
  }
});
